/**
 * 
 * If you have edited the file, please update
 * all the last-modified fields manually. Thanks!
 *
 * @last-modified by: 
 * @last-modified date: 
 * @last-modified time: 
 *
 * @author Swee Zhi
 * @date-created Sep 20, 2011    @time-created 1:56:37 PM
 *
 * @project: 
 * @module: 
 * @institution: 
 *
 */



/** 
 * note for usage of this validation class
 * paste this in faces-config.xml after <application> </application> tag
 * 
 *  <validator>
        <validator-id>checkValidEmail</validator-id>
        <validator-class>util.validation.EmailFormatValidator</validator-class>
    </validator>
 */
package util.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import util.localization.WebLocalization;


@ManagedBean
@RequestScoped
public class EmailFormatValidator implements Validator {
    //
    
    private WebLocalization localization;
    private String preferredLocale;
    
    public EmailFormatValidator() {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
    }

    @Override
    public void validate(FacesContext facesContext, UIComponent component, Object value) throws ValidatorException {
        String enteredEmail = (String)value;
        // only check when is not empty string
        if (!enteredEmail.isEmpty()) {
            Pattern p = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
            Matcher m = p.matcher(enteredEmail);
            boolean matchFound = m.matches();

            if (!matchFound) {
                FacesMessage message = new FacesMessage();
                message.setSeverity(FacesMessage.SEVERITY_ERROR);

                String errorMessage = "";
                if(preferredLocale.equals("en_US")) errorMessage = "Please enter a valid e-mail.";
                else if(preferredLocale.equals("en_SG")) errorMessage = "Please enter a valid e-mail.";
                else if(preferredLocale.equals("zh_CN")) errorMessage = "请输入有效的的电子邮箱。";
                else if(preferredLocale.equals("ms_MY")) errorMessage = "Sila masukkan e-mel yang sah.";

                message.setSummary(errorMessage);
                message.setDetail(null);
                throw new ValidatorException(message);
            }
        }
    }
    
}
